/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.edu.ifal.newnews.bd;

import br.edu.ifal.newnews.modelo.Categoria;
import br.edu.ifal.newnews.modelo.Usuario;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ifal
 */
public class CadastroCategoriaBD {
    
    public void insereCategoria(Categoria categoria) throws SQLException {

        Connection c = new ConexaoBD().abreConexao();

        String sql = "insert into tbCategoria"
                + "(codigo,nome,descricao)"
                + "values (?,?,?)";

        PreparedStatement stmt = null;

        try {
            stmt = c.prepareStatement(sql);


            stmt.setInt(1, categoria.getCodigo());
            stmt.setString(2, categoria.getNome());
            stmt.setString(3, categoria.getDescricao());
        
             stmt.execute();
            stmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(CadastroCategoriaBD.class.getName()).log(Level.SEVERE, null, ex);

        } finally {
            c.close();
        }
    }

    public void atualizaCategoria(Categoria c1) throws SQLException {

        Connection c = new ConexaoBD().abreConexao();

        String sql = " update tbCategoria set nome=?, descricao=? "
                + " where codigo=?";

        PreparedStatement stmt = c.prepareStatement(sql);

        stmt.setString(1, c1.getNome());
        stmt.setString(2, c1.getDescricao());
        stmt.setInt(3, c1.getCodigo());
       

        stmt.execute();
        stmt.close();
        c.close();

    }

    public void removeCategoria(Categoria categoria) throws SQLException {

        Connection c = new ConexaoBD().abreConexao();

        String sql = " delete from tbCategoria where codigo= ? ";

        PreparedStatement stmt = c.prepareStatement(sql);
        stmt.setInt(1,categoria.getCodigo());
        
        stmt.execute();
        stmt.close();
        c.close();

    }
    
    public Categoria buscaCategoriaPeloCodigo(int codigo) throws SQLException {
        Connection c = new ConexaoBD().abreConexao();

        String sql = "select * from tbCategoria where codigo= ?";
        PreparedStatement stmt = c.prepareStatement(sql);

        stmt.setInt(1, codigo);

        ResultSet rs = stmt.executeQuery();
        Categoria c1 = new Categoria();

        while (rs.next()) {
            

            c1.setNome(rs.getString("nome"));
            c1.setDescricao(rs.getString("descricao"));
           
        }
        rs.close();
        stmt.close();
        c.close();

        return c1;
    }
    
}
